import { axios } from '@/utils/request'
export default {
    blobSize: 1024 * 1024 * 5,
    fileKey: '',
    blobIndex: 0,
    blobCount: 1,
    uploading: [
        {
            progress: 0,
            fileName: '',
        }
    ],
    getFileResumableInfo: function(info){
        let that = this;
        that.blobCount =  Math.ceil(info.fileSize/that.blobSize);
        let data = {
            folderId: info.folderId,
            fileType: info.fileType,
            fileName: info.fileName,
            fileSize: info.fileSize,
            blobSize: that.blobSize,
            blobCount: that.blobCount
        }
        axios({
            url: '/sysfileinfo/GetFileResumableInfo',
            method: 'get',
            params: data
        }).then(res => {
            if(res.code === 200){
                that.fileKey = res.data.key;
                that.blobIndex = res.data.index;
                info.path = res.data.path;
                if(info.fileSize < that.blobSize){
                    that.uploadFragment(info.file, info);
                }else{
                    let fragment = that.cutFile(that.blobIndex, info.file)
                    that.uploadFragment(fragment, info);
                }
            }
        })
    },
    uploadFragment: function(file, info){
        let that = this;
        let postData = new FormData();
        postData.append('file', file);
        postData.append('path', info.path);
        if(that.blobCount > 1){
            postData.append('blobIndex', that.blobIndex);
            postData.append('key', that.fileKey);
        }
        axios({
            url: '/sysfileinfo/UploadFile',
            method: 'post',
            data: postData
        }).then(res => {
            if(res.code === 200&& res.data.result){
                if(that.blobIndex < that.blobCount - 1){
                    that.blobIndex++;
                    let fragment = that.cutFile(that.blobIndex, info.file)
                    that.uploadFragment(fragment, info);
                    if(info.uploading){
                        let num = Number( parseFloat(that.blobIndex / that.blobCount).toFixed(2))*100;
                        num=parseInt(num);
                        info.uploading(info.file, num)
                    }
                }else{
                    if(info.callBack){
                        info.callBack(res.data);
                    }
                    if(info.uploading){
                        info.uploading(info.file, 100)
                    }
                }
            }
        })
    },
    cutFile(startIndex, file){
        let that = this;
        let startPosition = startIndex * that.blobSize;
        let endPosition = startPosition + that.blobSize;
        let fragment = file.slice(startPosition, endPosition)
        return fragment;
    },
}